package com.example.wangzh.developkit.utils.count_down_manager;


/**
 * Created by zhwang16 on 2017/12/13.
 * 实现计时器功能，可以设置计时周期、循环次数、每次循环时执行的动作，计时结束时执行的动作
 * 可以中断计时，重新开始计时
 */

public class CountDownManager {
    public interface ITime {
        void onTick(long millisUntilFinished);

        void onFinish();
    }

    private ITime iTime;

    private long period = 1000;
    private int repeatTimes = 1;
    MyCountDownTimer myCountDownTimer;

    public CountDownManager(long period, int repeatTimes) {
        this.period = period;
        this.repeatTimes = repeatTimes;
    }

    public CountDownManager() {

    }

    public long getPeriod() {
        return period;
    }

    public void setPeriod(long period) {
        this.period = period;
    }

    public int getRepeatTimes() {
        return repeatTimes;
    }

    public void setRepeatTimes(int repeatTimes) {
        this.repeatTimes = repeatTimes;
    }

    public void setITime(ITime iTime) {
        this.iTime = iTime;
    }

    /**
     * 开始计时器
     */
    public void start() {
        cancel();
        myCountDownTimer = new MyCountDownTimer(period * repeatTimes, period) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (null != iTime) {
                    iTime.onTick(millisUntilFinished);
                }
            }

            @Override
            public void onFinish() {
                if (null != iTime) {
                    iTime.onFinish();
                }
            }
        };
        myCountDownTimer.start();
    }

    /**
     * 取消计时器
     */
    public void cancel() {
        if (null != myCountDownTimer) {
            myCountDownTimer.cancel();
            myCountDownTimer = null;
        }
    }

}
